package config

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"os"
	"time"
)

type Config struct {
	AccountService  AccountService
	SecurityService SecurityService
	PostService     PostService
	ApiService      ApiService
	Database        Database
}

type Database struct {
	Address string
	Name    string
	User    string
	Pass    string
	Port    int
}

const (
	CONFIGFILE = "config/config.yaml"
)

var (
	config *Config
	status bool
)

func init() {
	config = new(Config)
	if _, err := os.Stat(CONFIGFILE); err == nil {
		status = loadFromFile()
	}
	if !status {
		loadFromDefault()
	}
}

func loadFromFile() bool {
	fileBytes, err := ioutil.ReadFile(CONFIGFILE)
	if err != nil {
		return false
	}
	if err = yaml.Unmarshal(fileBytes, config); err != nil {
		return false
	}
	return true
}

func loadFromDefault() {
	//service :=
	config = &Config{
		ApiService: ApiService{
			Name:    "lab.api",
			Version: "1.0",
		},
		AccountService: AccountService{
			Name:    "lab.account",
			Version: "1.0",
		},
		PostService: PostService{
			Name:    "lab.post",
			Version: "1.0",
		},
		SecurityService: SecurityService{
			Name:    "lab.security",
			Version: "1.0",
			Security: Security{
				GlobalToken:    "BeSureToChange",
				InitRole:       1,
				JwtExpire:      4 * time.Hour,
				RandKeyExpiry:  4 * time.Hour,
				RememberExpiry: 2 * 24 * time.Hour,
				RandKeyLen:     8,
				RandKeyEnable:  false,
			},
		},
		Database: Database{
			Address: "localhost",
			Name:    "lab",
			Port:    5432,
			User:    "housirvip",
			Pass:    "",
		},
	}
	data, err := yaml.Marshal(config)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	err = ioutil.WriteFile(CONFIGFILE, data, os.ModePerm)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
}

func GetConfig() Config {
	return *config
}
